package master

import (
	"context"
	"crontab/common"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

var (
	G_LogMgr *LogMgr
)

type JobNameFilter struct {
	JobName string `bson:"jobName"`
}

type SortLogByStartTime struct {
	SortOrder int `bson:"startTime"`
}

type LogMgr struct {
	Client *mongo.Client
	Db *mongo.Database
	Collection *mongo.Collection
}

// 获取日志列表
func (l *LogMgr) ListLog(jobName string,skip,limit int) (jobList []*common.JobLog,err error) {
	var (
		filter *JobNameFilter
		sort *SortLogByStartTime
		limitInt64 int64
		skip64 int64
		cur *mongo.Cursor
		jobLog *common.JobLog
	)
	jobList = make([]*common.JobLog,0)
	filter = &JobNameFilter{JobName: jobName}
	sort = &SortLogByStartTime{SortOrder: -1}
	limitInt64 = int64(limit)
	skip64 = int64(skip)
	cur,err = l.Collection.Find(context.TODO(),filter,&options.FindOptions{
		Sort: sort,
		Limit: &limitInt64,
		Skip: &skip64,
	})
	if err != nil {
		return
	}
	for cur.Next(context.TODO()) {
		jobLog = &common.JobLog{}
		if err = cur.Decode(jobLog); err != nil {
			continue
		}
		jobList = append(jobList,jobLog)
	}

	return
}

// 初始化日志
func InitLogMgr() (err error) {
	var (
		optionsClient *options.ClientOptions
		logMgr *LogMgr
	)
	optionsClient = options.Client()

	logMgr = &LogMgr{}
	// 详解: https://blog.csdn.net/pursuer211/article/details/82994027
	logMgr.Client,err = mongo.Connect(
		context.TODO(),
		optionsClient.ApplyURI(G_Config.MongoUri),
		optionsClient.SetConnectTimeout(time.Duration(G_Config.MongoTimeout) * time.Second),  // MongoDB Client需要找到可用的MongoDB Server
		optionsClient.SetServerSelectionTimeout(time.Duration(G_Config.MongoTimeout) * time.Second), // MongoDB Client需要和MongoDB Server建立（new）Connection
		)
	if err != nil {
		return
	}

	// 检查连接
	err = logMgr.Client.Ping(context.TODO(),nil)
	if err != nil {
		return
	}

	logMgr.Db = logMgr.Client.Database("cron")
	logMgr.Collection = logMgr.Db.Collection("log")

	G_LogMgr = logMgr
	return
}

